import React, { useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Card, Button, Form, Input, message } from "antd";
import {
  reqAddHospitalSetApi,
  reqUpdateHospitalSetApi,
  reqGetHospitalItemApi,
} from "@api/hospital";
import type { HospitalListItem } from "@/api/hospital/model/hospitalListType";

export default function AddOrUpdateHospitalSet() {
  // 从路由参数上获取id
  const { id } = useParams();
  const navigate = useNavigate();
  const [form] = Form.useForm();

  useEffect(() => {
    // 组件挂载时，如果有id则请求当前id的医院设置信息
    if(id){
      getHospitalSetItem(+id)
    }
  }, []);

  // 保存按钮
  async function onFinish(hospitalInfo: HospitalListItem) {
    if (id) {
      // 更新医院
      hospitalInfo.id = +id
      await reqUpdateHospitalSetApi(hospitalInfo);
    } else {
      // 添加医院
      await reqAddHospitalSetApi(hospitalInfo);
    }
    message.success(`${id ? "修改" : "添加"}医院成功`);
    navigate("/syt/hospital/hospitalset");
    form.resetFields();
  }

  // 根据医院id获取一条医院设置
  async function getHospitalSetItem(id:number){
    const res = await reqGetHospitalItemApi(id)
    // 将请求的数据直接赋值给表单
    form.setFieldsValue(res)
  }

  // 跳转到医院设置页
  function goHospitalList() {
    form.resetFields();
    navigate("/syt/hospital/hospitalset");
  }

  return (
    <Card>
      <Form
        form={form}
        style={{ marginBottom: 20 }}
        onFinish={onFinish}
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 21 }}
      >
        <Form.Item
          name="hosname"
          label="医院名称"
          rules={[{ required: true, message: "请输入医院名称!" }]}
        >
          <Input placeholder="请输入医院名称" />
        </Form.Item>
        <Form.Item
          name="hoscode"
          label="医院编号"
          rules={[{ required: true, message: "请输入医院编号!" }]}
        >
          <Input placeholder="请输入医院编号" />
        </Form.Item>
        <Form.Item
          name="apiUrl"
          label="api基础路径"
          rules={[{ required: true, message: "请输入api基础路径!" }]}
        >
          <Input placeholder="请输入api基础路径" />
        </Form.Item>
        <Form.Item
          name="contactsName"
          label="联系人姓名"
          rules={[{ required: true, message: "请输入联系人姓名!" }]}
        >
          <Input placeholder="请输入联系人姓名" />
        </Form.Item>
        <Form.Item
          name="contactsPhone"
          label="联系人手机"
          rules={[{ required: true, message: "请输入联系人姓名!" }]}
        >
          <Input placeholder="请输入联系人姓名" />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 3, span: 21 }}>
          <Button type="primary" htmlType="submit" style={{ marginRight: 20 }}>
            保存
          </Button>
          <Button onClick={goHospitalList}>返回</Button>
        </Form.Item>
      </Form>
    </Card>
  );
}
